import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
import Lx from "../views/Lx.vue";
import Login from "../views/Login.vue";
import Register from "../views/Register.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/login",
    component: Login,
  },
  {
    path: "/register",
    component: Register,
  },
  {
    path: "/lx",
    component: Lx,
  },
  {
    path: "/",
    component: Home,
    children: [
      {
        path: "/",
        name: "home",
        component: () =>
          import(/* webpackChunkName: "/miste" */ "../views/Miste.vue"),
        meta: { title: "鲜花-首页" },
      },
      {
        path: "/product",
        name: "Product",
        component: () =>
          import(/* webpackChunkName: "/Product" */ "../views/Product.vue"),
      },
      {
        path: "/chanpin",
        name: "Chanpin",
        component: () =>
          import(/* webpackChunkName: "/Chanpin" */ "../views/Chanpin.vue"),
      },
      {
        path: "/xinwen",
        name: "XinWen",
        component: () =>
          import(/* webpackChunkName: "/XinWen" */ "../views/XinWen.vue"),
      },
      {
        path: "/news",
        name: "News",
        component: () =>
          import(/* webpackChunkName: "/News" */ "../views/News.vue"),
      },
      {
        path: "/kehu",
        name: "Kehu",
        component: () =>
          import(/* webpackChunkName: "/Kehu" */ "../views/Kehu.vue"),
      },
      {
        path: "/photo",
        name: "Photo",
        component: () =>
          import(/* webpackChunkName: "/Photo" */ "../views/Photo.vue"),
      },
      {
        path: "/contact",
        name: "Contact",
        component: () =>
          import(/* webpackChunkName: "/Contact" */ "../views/Contact.vue"),
      },
      {
        path: "/login",
        name: "Login",
        component: () => import("../views/Login.vue"),
      },
      {
        path: "/register",
        name: "Register",
        component: () => import("../views/Register.vue"),
      },
    ],
  },
  {
    path: "/error",
    name: "notFound",
    component: () => import("../views/Error.vue"),
  },
  {
    path: "*", // 页面不存在的情况下会跳到404页面
    redirect: "/error",
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});
router.beforeEach((to, from, next) => {
  //登录及注册页面可以直接进入,而主页面需要分情况
  if (to.path == "/login") {
    next();
    console.log(localStorage.s);
  } else if (to.path == "/register") {
    next();
  } else {
    if (from.path == "/login") {
      //从登录页面可以直接通过登录进入主页面
      next();
    } else {
      //从/进入,如果登录状态是true，则直接next进入主页面
      if (localStorage.s === "true") {
        next();
        console.log(localStorage["s"]);
      } else {
        //如果登录状态是false，那么跳转至登录页面,需要登录才能进入主页面
        next("/login");
        console.log("需要登录");
      }
    }
  }
});
export default router;
